# Copyright (c) 2024, kaepyz@gmail.com and contributors
# For license information, please see license.txt

import frappe
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from frappe.utils import now, add_days, get_datetime


class OrderSyncService:
    """订单同步服务"""
    
    def __init__(self):
        self.settings = frappe.get_single('Tongtool Settings')
        if not self.settings.app_key or not self.settings.app_secret:
            frappe.throw("请先在通途设置中配置API凭证")
        
        from tongtool_integration.api.orders import OrderAPI
        self.order_api = OrderAPI()
    
    def sync_daily_orders(self, target_date: str = None) -> Dict:
        """
        同步指定日期的订单
        
        Args:
            target_date: 目标日期 '2024-08-28'，为None时同步昨天
            
        Returns:
            Dict: 同步结果统计
        """
        if not target_date:
            target_date = add_days(frappe.utils.today(), -1)
        
        result = {
            'date': target_date,
            'self_fulfillment': {'total': 0, 'created': 0, 'updated': 0, 'errors': 0},
            'fba': {'total': 0, 'created': 0, 'updated': 0, 'errors': 0},
            'errors': []
        }
        
        try:
            frappe.logger().info(f"开始同步 {target_date} 的订单")
            
            # 1. 同步自发货订单
            self._sync_self_fulfillment_orders(target_date, result['self_fulfillment'], result['errors'])
            
            # 2. 同步FBA订单
            self._sync_fba_orders(target_date, result['fba'], result['errors'])
            
            # 3. 更新设置中的最后同步时间
            self.settings.last_sync_time = now()
            self.settings.save()
            
            frappe.logger().info(f"订单同步完成: {result}")
            
        except Exception as e:
            error_msg = f"订单同步失败: {str(e)}"
            frappe.log_error(error_msg)
            result['errors'].append(error_msg)
        
        return result
    
    def _sync_self_fulfillment_orders(self, date: str, result: Dict, errors: List):
        """同步自发货订单"""
        try:
            page_no = 1
            
            while True:
                try:
                    orders, is_last_page = self.order_api.get_orders({
                        'sale_date_from': f'{date} 00:00:00',
                        'sale_date_to': f'{date} 23:59:59',
                        'page_no': page_no,
                        'page_size': 100
                    })
                    
                    for order_data in orders:
                        try:
                            if self._process_order(order_data, '自发货'):
                                result['created'] += 1
                            else:
                                result['updated'] += 1
                            result['total'] += 1
                            
                        except Exception as e:
                            error_msg = f"处理自发货订单失败 {order_data.get('orderIdCode')}: {str(e)}"
                            frappe.log_error(error_msg)
                            errors.append(error_msg)
                            result['errors'] += 1
                    
                    if is_last_page:
                        break
                        
                    page_no += 1
                    
                except Exception as e:
                    error_msg = f"获取自发货订单失败（第{page_no}页）: {str(e)}"
                    frappe.log_error(error_msg)
                    errors.append(error_msg)
                    break
                    
        except Exception as e:
            error_msg = f"同步自发货订单失败: {str(e)}"
            frappe.log_error(error_msg)
            errors.append(error_msg)
    
    def _sync_fba_orders(self, date: str, result: Dict, errors: List):
        """同步FBA订单"""
        try:
            fba_orders = self.order_api.get_fba_orders({
                'purchase_date_from': f'{date} 00:00:00',
                'purchase_date_to': f'{date} 23:59:59',
                'page_no': 1,
                'page_size': 100
            })
            
            for order_data in fba_orders:
                try:
                    if self._process_fba_order(order_data):
                        result['created'] += 1
                    else:
                        result['updated'] += 1
                    result['total'] += 1
                    
                except Exception as e:
                    error_msg = f"处理FBA订单失败 {order_data.get('orderId')}: {str(e)}"
                    frappe.log_error(error_msg)
                    errors.append(error_msg)
                    result['errors'] += 1
                    
        except Exception as e:
            error_msg = f"同步FBA订单失败: {str(e)}"
            frappe.log_error(error_msg)
            errors.append(error_msg)
    
    def _process_order(self, order_data: Dict, order_type: str) -> bool:
        """
        处理单个自发货订单
        
        Returns:
            bool: True表示新创建，False表示更新
        """
        order_id = order_data['orderIdCode']
        
        # 检查订单是否已存在
        existing = frappe.get_value("Tongtool Order", {"order_id_code": order_id}, "name")
        
        if existing:
            self._update_order(existing, order_data, order_type)
            return False
        else:
            self._create_order(order_data, order_type)
            return True
    
    def _process_fba_order(self, order_data: Dict) -> bool:
        """
        处理单个FBA订单
        
        Returns:
            bool: True表示新创建，False表示更新
        """
        # FBA订单使用orderId作为标识
        order_id = order_data.get('orderId')
        if not order_id:
            raise Exception("FBA订单缺少orderId")
        
        # 检查订单是否已存在
        existing = frappe.get_value("Tongtool Order", {"order_id_code": order_id}, "name")
        
        if existing:
            self._update_fba_order(existing, order_data)
            return False
        else:
            self._create_fba_order(order_data)
            return True
    
    def _create_order(self, order_data: Dict, order_type: str):
        """创建新的自发货订单"""
        # 处理订单商品明细
        order_items = self._process_order_items(
            order_data.get('orderDetails', []), 
            order_data.get('goodsInfo', {})
        )
        
        # 提取包裹信息
        package_info = order_data.get('packageInfoList', [])
        package_id = package_info[0].get('packageId') if package_info else ''
        tracking_number = package_info[0].get('trackingNumber') if package_info else ''
        
        # 创建订单文档
        order = frappe.get_doc({
            'doctype': 'Tongtool Order',
            'order_id_code': order_data['orderIdCode'],
            'platform_order_id': order_data.get('salesRecordNumber'),
            'order_type': order_type,
            'order_status': self._map_order_status(order_data.get('orderStatus')),
            'sale_time': self._parse_timestamp(order_data.get('saleTime')),
            'paid_time': self._parse_timestamp(order_data.get('paidTime')),
            'buyer_name': order_data.get('buyerName'),
            'buyer_email': order_data.get('buyerEmail'),
            'buyer_country': order_data.get('buyerCountry'),
            'receive_address': order_data.get('receiveAddress'),
            'platform_code': order_data.get('platformCode'),
            'sale_account': order_data.get('saleAccount'),
            'warehouse_name': order_data.get('warehouseName'),
            # 包裹和运费信息
            'package_id': package_id,
            'tracking_number': tracking_number,
            'merchant_carrier_shortname': order_data.get('merchantCarrierShortname'),
            'shipping_fee': order_data.get('shippingFee', 0),
            # 金额信息
            'order_amount': order_data.get('orderAmount', 0),
            'order_amount_currency': order_data.get('orderAmountCurrency', 'USD'),
            'products_total_price': order_data.get('productsTotalPrice', 0),
            'shipping_fee_income': order_data.get('shippingFeeIncome', 0),
            'platform_fee': order_data.get('platformFee', 0),
            'actual_total_price': order_data.get('actualTotalPrice', 0),
            'sync_status': '已同步',
            'last_sync_time': now(),
            'order_items': order_items,
            'raw_data': order_data
        })
        
        order.insert()
        frappe.db.commit()
        
        frappe.logger().info(f"创建自发货订单: {order.order_id_code}")
    
    def _create_fba_order(self, order_data: Dict):
        """创建新的FBA订单"""
        # 处理FBA订单商品明细
        order_items = self._process_fba_order_items(order_data.get('orderItem', []))
        
        # 安全获取数值字段，处理None值
        total_item_price = order_data.get('totalItemPrice') or 0
        total_shipping_price = order_data.get('totalShippingPrice') or 0
        
        order = frappe.get_doc({
            'doctype': 'Tongtool Order',
            'order_id_code': order_data['orderId'],
            'platform_order_id': order_data.get('orderId'),
            'order_type': 'FBA',
            'order_status': '已发货',  # FBA订单默认已发货
            'sale_time': self._parse_fba_timestamp(order_data.get('purchaseDate')),
            'paid_time': self._parse_timestamp(order_data.get('paymentsDate')),
            'buyer_name': order_data.get('recipientName'),
            'buyer_email': order_data.get('buyerEmail'),
            'buyer_country': order_data.get('shipCountry'),
            'receive_address': self._format_fba_address(order_data),
            'platform_code': 'amazon',
            'sale_account': order_data.get('account'),  # 使用account字段而不是salesChannel
            'channel': order_data.get('salesChannel'),  # salesChannel存到channel字段
            'warehouse_name': 'Amazon FBA',
            'order_amount': total_item_price + total_shipping_price,
            'order_amount_currency': order_data.get('currency', 'USD'),
            'products_total_price': total_item_price,
            'shipping_fee_income': total_shipping_price,
            'platform_fee': 0,  # FBA订单平台费用需要从其他地方获取
            'sync_status': '已同步',
            'last_sync_time': now(),
            'order_items': order_items,
            'raw_data': order_data
        })
        
        order.insert()
        frappe.db.commit()
        
        frappe.logger().info(f"创建FBA订单: {order.order_id_code}")
    
    def _update_order(self, existing_name: str, order_data: Dict, order_type: str):
        """更新现有订单"""
        order = frappe.get_doc("Tongtool Order", existing_name)
        
        # 更新可能变化的字段
        order.order_status = self._map_order_status(order_data.get('orderStatus'))
        order.paid_time = self._parse_timestamp(order_data.get('paidTime'))
        order.platform_fee = order_data.get('platformFee', 0)
        order.actual_total_price = order_data.get('actualTotalPrice', 0)
        order.last_sync_time = now()
        order.raw_data = order_data
        
        # 更新订单明细
        self._update_order_items(order, order_data.get('orderDetails', []), order_data.get('goodsInfo', {}))
        
        order.save()
        frappe.db.commit()
        
        frappe.logger().info(f"更新自发货订单: {order.order_id_code}")
    
    def _update_fba_order(self, existing_name: str, order_data: Dict):
        """更新现有FBA订单"""
        order = frappe.get_doc("Tongtool Order", existing_name)
        
        # 安全获取数值字段，处理None值
        total_item_price = order_data.get('totalItemPrice') or 0
        total_shipping_price = order_data.get('totalShippingPrice') or 0
        
        # 更新FBA订单字段
        order.products_total_price = total_item_price
        order.shipping_fee_income = total_shipping_price
        order.order_amount = total_item_price + total_shipping_price
        order.last_sync_time = now()
        order.raw_data = order_data
        order.sale_account = order_data.get('account')  # 更新account字段
        order.channel = order_data.get('salesChannel')
        
        # 更新FBA订单商品明细
        self._update_fba_order_items(order, order_data.get('orderItem', []))
        
        order.save()
        frappe.db.commit()
        
        frappe.logger().info(f"更新FBA订单: {order.order_id_code}")
    
    def _process_order_items(self, order_details: List[Dict], goods_info: Dict = None) -> List[Dict]:
        """处理订单商品明细"""
        items = []
        
        # 创建通途商品信息映射表，便于查找
        tongtool_goods_map = {}
        if goods_info and goods_info.get('tongToolGoodsInfoList'):
            for goods in goods_info['tongToolGoodsInfoList']:
                sku = goods.get('goodsSku')
                if sku:
                    tongtool_goods_map[sku] = goods
        
        for detail in order_details:
            # 修复字段名大小写问题
            tongtool_sku = detail.get('goodsMatchedSku') or detail.get('goodsSku')
            platform_sku = detail.get('webStoreSku') or detail.get('webstore_sku')
            
            # SKU匹配
            erp_item_code = None
            match_status = '未匹配'
            item_cost = 0
            item_name = None
            
            if tongtool_sku:
                erp_item_code = self._find_erp_item_by_tongtool_sku(tongtool_sku)
                if erp_item_code:
                    match_status = '已匹配'
                
                # 从通途商品信息获取成本和名称
                if tongtool_sku in tongtool_goods_map:
                    goods = tongtool_goods_map[tongtool_sku]
                    item_cost = goods.get('goodsCurrentCost', 0) or goods.get('goodsAverageCost', 0)
                    item_name = goods.get('productName') or goods.get('goodsTitle')
            
            items.append({
                'platform_sku': platform_sku,
                'tongtool_sku': tongtool_sku,
                'erp_item_code': erp_item_code,
                'quantity': detail.get('quantity', 1),
                'transaction_price': detail.get('transactionPrice', 0) or detail.get('transaction_price', 0),
                'item_tax': 0,  # 自发货订单通常没有单独的商品税费
                'web_store_item_id': detail.get('webStoreItemId') or detail.get('webstore_item_id'),
                'goods_detail_id': detail.get('goodsDetailId'),
                'asin': '',  # 自发货订单通常没有ASIN
                'match_status': match_status,
                'item_cost': item_cost,
                'tongtool_item_name': item_name
            })
        
        return items
    
    def _process_fba_order_items(self, order_items: List[Dict]) -> List[Dict]:
        """
        处理FBA订单商品明细
        
        Args:
            order_items: FBA订单的orderItem数组
            
        Returns:
            List[Dict]: 处理后的订单商品明细
        """
        items = []
        
        for item in order_items:
            # 提取SKU信息
            platform_sku = item.get('sku') or ''
            tongtool_sku = item.get('goodsSku') or ''
            
            # 提取商品名称
            item_name = item.get('productName') or ''
            
            # SKU匹配
            erp_item_code = ''
            match_status = '未匹配'
            item_cost = 0
            
            if tongtool_sku:
                erp_item_code = self._find_erp_item_by_tongtool_sku(tongtool_sku)
                if erp_item_code:
                    match_status = '已匹配'
                    # 尝试获取物料成本
                    try:
                        item_cost = frappe.db.get_value("Item", erp_item_code, "standard_rate") or 0
                    except:
                        item_cost = 0
            
            # 处理数值字段，确保不为None
            quantity = item.get('quantityPurchased', 1) or 1
            item_price = item.get('itemPrice', 0) or 0
            item_tax = item.get('itemTax', 0) or 0
            
            items.append({
                'platform_sku': platform_sku,
                'tongtool_sku': tongtool_sku,
                'erp_item_code': erp_item_code,
                'quantity': quantity,
                'transaction_price': item_price,
                'item_tax': item_tax,
                'web_store_item_id': item.get('orderItemId') or '',
                'goods_detail_id': item.get('amazonId') or '',
                'asin': item.get('asin') or '',
                'match_status': match_status,
                'item_cost': item_cost,
                'tongtool_item_name': item_name
            })
        
        return items
    
    def _update_fba_order_items(self, order, order_items: List[Dict]):
        """更新FBA订单商品明细"""
        # 清空现有明细
        order.order_items = []
        
        # 重新处理商品明细
        new_items = self._process_fba_order_items(order_items)
        for item_data in new_items:
            order.append('order_items', item_data)
    
    def refresh_order_from_raw_data(self, order_name: str) -> Dict:
        """
        从raw_data重新解析单个订单的数据，更新缺失字段
        
        Args:
            order_name: 订单文档名称
            
        Returns:
            Dict: 刷新结果
        """
        try:
            order = frappe.get_doc("Tongtool Order", order_name)
            if not order.raw_data:
                return {"success": False, "message": "订单没有raw_data数据"}
            
            # 解析raw_data
            import json
            if isinstance(order.raw_data, str):
                raw_data = json.loads(order.raw_data)
            else:
                raw_data = order.raw_data
            
            updated_fields = []
            
            # 根据订单类型重新处理
            if order.order_type == "FBA":
                updated_fields = self._refresh_fba_order_from_raw_data(order, raw_data)
            else:
                updated_fields = self._refresh_self_fulfillment_order_from_raw_data(order, raw_data)
            
            # 保存更改
            order.save()
            frappe.db.commit()
            
            return {
                "success": True, 
                "message": f"成功刷新订单 {order.order_id_code}",
                "updated_fields": updated_fields
            }
            
        except Exception as e:
            frappe.log_error(f"刷新订单失败 {order_name}: {str(e)}")
            return {"success": False, "message": f"刷新失败: {str(e)}"}
    
    def _refresh_fba_order_from_raw_data(self, order, raw_data: Dict) -> List[str]:
        """从raw_data刷新FBA订单"""
        updated_fields = []
        
        # 更新主表字段
        if not order.sale_account and raw_data.get('account'):
            order.sale_account = raw_data.get('account')
            updated_fields.append('sale_account')
            
        if not order.channel and raw_data.get('salesChannel'):
            order.channel = raw_data.get('salesChannel')
            updated_fields.append('channel')
        
        # 重新处理商品明细
        order_items = raw_data.get('orderItem', [])
        if order_items:
            # 清空现有明细
            order.order_items = []
            
            # 重新处理商品明细
            new_items = self._process_fba_order_items(order_items)
            for item_data in new_items:
                order.append('order_items', item_data)
            
            updated_fields.append('order_items')
        
        return updated_fields
    
    def _refresh_self_fulfillment_order_from_raw_data(self, order, raw_data: Dict) -> List[str]:
        """从raw_data刷新自发货订单"""
        updated_fields = []
        
        # 更新包裹信息
        package_info = raw_data.get('packageInfoList', [])
        if package_info:
            if not order.package_id and package_info[0].get('packageId'):
                order.package_id = package_info[0].get('packageId')
                updated_fields.append('package_id')
                
            if not order.tracking_number and package_info[0].get('trackingNumber'):
                order.tracking_number = package_info[0].get('trackingNumber')
                updated_fields.append('tracking_number')
        
        # 更新运费信息
        if not order.merchant_carrier_shortname and raw_data.get('merchantCarrierShortname'):
            order.merchant_carrier_shortname = raw_data.get('merchantCarrierShortname')
            updated_fields.append('merchant_carrier_shortname')
            
        if not order.shipping_fee and raw_data.get('shippingFee'):
            order.shipping_fee = raw_data.get('shippingFee', 0)
            updated_fields.append('shipping_fee')
        
        # 重新处理商品明细
        order_details = raw_data.get('orderDetails', [])
        goods_info = raw_data.get('goodsInfo', {})
        if order_details:
            # 清空现有明细
            order.order_items = []
            
            # 重新处理商品明细
            new_items = self._process_order_items(order_details, goods_info)
            for item_data in new_items:
                order.append('order_items', item_data)
            
            updated_fields.append('order_items')
        
        return updated_fields
    
    def rematch_all_orders(self):
        """重新匹配所有未匹配的订单商品SKU"""
        try:
            # 查找所有有未匹配商品的订单
            orders = frappe.get_all("Tongtool Order", 
                filters={"match_status": "未匹配"}, 
                fields=["name", "order_id_code"]
            )
            
            matched_count = 0
            processed_count = 0
            
            for order_info in orders:
                order = frappe.get_doc("Tongtool Order", order_info.name)
                order_updated = False
                
                for item in order.order_items:
                    if item.match_status == '未匹配' and item.tongtool_sku:
                        erp_item_code = self._find_erp_item_by_tongtool_sku(item.tongtool_sku)
                        if erp_item_code:
                            item.erp_item_code = erp_item_code
                            item.match_status = '已匹配'
                            matched_count += 1
                            order_updated = True
                
                if order_updated:
                    # 重新计算订单匹配状态
                    unmatched_items = [item for item in order.order_items if item.match_status == '未匹配']
                    if not unmatched_items:
                        order.match_status = '已匹配'
                    elif len(unmatched_items) < len(order.order_items):
                        order.match_status = '部分匹配'
                    
                    order.save()
                    processed_count += 1
            
            frappe.db.commit()
            
            frappe.msgprint(f"重新匹配完成！处理订单：{processed_count}个，匹配商品：{matched_count}个")
            return {"processed_orders": processed_count, "matched_items": matched_count}
            
        except Exception as e:
            frappe.log_error(f"重新匹配订单失败: {str(e)}")
            frappe.throw(f"重新匹配失败: {str(e)}")
    
    def _find_erp_item_by_tongtool_sku(self, tongtool_sku: str) -> Optional[str]:
        """通过通途SKU查找ERPNext物料"""
        try:
            item_code = frappe.db.sql("""
                SELECT DISTINCT parent as item_code
                FROM `tabItem Customer Detail` 
                WHERE ref_code = %s
                ORDER BY 
                    CASE 
                        WHEN customer_name = '通途' THEN 1
                        WHEN customer_group = '电商平台' THEN 2
                        WHEN customer_name IS NULL AND customer_group IS NULL THEN 3
                        ELSE 4
                    END
                LIMIT 1
            """, (tongtool_sku,))
            
            return item_code[0][0] if item_code else None
            
        except Exception as e:
            frappe.log_error(f"查找ERPNext物料失败 {tongtool_sku}: {str(e)}")
            return None
    
    def _update_order_items(self, order, order_details: List[Dict], goods_info: Dict = None):
        """更新订单明细"""
        # 清除现有明细并重新处理（简化逻辑，确保数据一致性）
        order.order_items = []
        
        # 重新处理明细
        items = self._process_order_items(order_details, goods_info)
        for item in items:
            order.append('order_items', item)
    
    def _map_order_status(self, status: str) -> str:
        """映射订单状态"""
        status_mapping = {
            'waitPacking': '等待配货',
            'waitPrinting': '等待打印', 
            'waitingDespatching': '等待发货',
            'despatched': '已发货',
            'unpaid': '未付款',
            'payed': '已付款'
        }
        return status_mapping.get(status, status or '未知')
    
    def _parse_timestamp(self, timestamp_str: str) -> Optional[datetime]:
        """解析时间戳字符串"""
        if not timestamp_str:
            return None
        
        try:
            return get_datetime(timestamp_str)
        except:
            return None
    
    def _parse_fba_timestamp(self, timestamp: int) -> Optional[datetime]:
        """解析FBA时间戳（毫秒）"""
        if not timestamp:
            return None
        
        try:
            return datetime.fromtimestamp(timestamp / 1000)
        except:
            return None
    
    def _format_fba_address(self, order_data: Dict) -> str:
        """格式化FBA地址"""
        address_parts = []
        
        for field in ['shipAddress1', 'shipAddress2', 'shipAddress3', 'shipCity', 'shipState', 'shipPostalCode', 'shipCountry']:
            value = order_data.get(field)
            if value:
                address_parts.append(value)
        
        return ', '.join(address_parts)


# 定时任务函数
@frappe.whitelist()
def sync_yesterday_orders():
    """同步昨天的订单（定时任务）"""
    try:
        sync_service = OrderSyncService()
        result = sync_service.sync_daily_orders()
        
        # 发送通知（如果启用）
        settings = frappe.get_single('Tongtool Settings')
        if settings.enable_error_notification and settings.notification_email:
            if result['self_fulfillment']['errors'] > 0 or result['fba']['errors'] > 0:
                send_sync_error_notification(result, settings.notification_email)
        
        return result
        
    except Exception as e:
        frappe.log_error(f"定时同步订单失败: {str(e)}")
        return {'error': str(e)}


@frappe.whitelist()
def refresh_single_order(order_name: str):
    """刷新单个订单（白名单方法，可从前端调用）"""
    try:
        sync_service = OrderSyncService()
        result = sync_service.refresh_order_from_raw_data(order_name)
        
        if result['success']:
            frappe.msgprint(
                f"订单刷新成功！<br>更新字段: {', '.join(result['updated_fields'])}",
                title="刷新成功",
                indicator="green"
            )
        else:
            frappe.msgprint(
                f"订单刷新失败: {result['message']}",
                title="刷新失败", 
                indicator="red"
            )
        
        return result
        
    except Exception as e:
        frappe.log_error(f"刷新单个订单失败: {str(e)}")
        frappe.msgprint(f"刷新失败: {str(e)}", title="错误", indicator="red")
        return {'success': False, 'error': str(e)}


@frappe.whitelist()
def bulk_refresh_orders(order_names: str = None, filters: str = None, use_queue: bool = True):
    """
    批量刷新订单
    
    Args:
        order_names: 订单名称列表(JSON字符串)
        filters: 过滤条件(JSON字符串)
        use_queue: 是否使用队列处理
    """
    try:
        import json
        
        # 获取要刷新的订单列表
        if order_names:
            names = json.loads(order_names) if isinstance(order_names, str) else order_names
            orders = frappe.get_all("Tongtool Order", 
                filters={"name": ["in", names]},
                fields=["name", "order_id_code", "order_type"]
            )
        elif filters:
            filter_dict = json.loads(filters) if isinstance(filters, str) else filters
            orders = frappe.get_all("Tongtool Order", 
                filters=filter_dict,
                fields=["name", "order_id_code", "order_type"]
            )
        else:
            # 默认刷新所有有问题的订单
            # 由于Frappe的OR查询语法问题，分别查询然后合并
            order_names_set = set()
            
            # 查找未匹配的订单
            unmatched_orders = frappe.get_all("Tongtool Order", 
                filters={"match_status": "未匹配"},
                fields=["name"]
            )
            order_names_set.update([o.name for o in unmatched_orders])
            
            # 查找sale_account为空的订单
            empty_account_orders = frappe.get_all("Tongtool Order", 
                filters={"sale_account": ["in", ["", "None", None]]},
                fields=["name"]
            )
            order_names_set.update([o.name for o in empty_account_orders])
            
            # 查找channel为空的订单
            empty_channel_orders = frappe.get_all("Tongtool Order", 
                filters={"channel": ["in", ["", "None", None]]},
                fields=["name"]
            )
            order_names_set.update([o.name for o in empty_channel_orders])
            
            # 获取完整的订单信息
            if order_names_set:
                orders = frappe.get_all("Tongtool Order", 
                    filters={"name": ["in", list(order_names_set)]},
                    fields=["name", "order_id_code", "order_type"]
                )
            else:
                orders = []
        
        if not orders:
            frappe.msgprint("没有找到需要刷新的订单", indicator="orange")
            return {"success": True, "total": 0}
        
        if use_queue and len(orders) > 10:
            # 大批量使用队列处理
            job = frappe.enqueue(
                'tongtool_integration.sync.order_sync.process_bulk_refresh_queue',
                queue='default',
                timeout=3600,
                order_names=[o.name for o in orders],
                now=False
            )
            
            frappe.msgprint(
                f"已启动批量刷新任务，共 {len(orders)} 个订单。任务ID: {job.id}",
                title="批量刷新",
                indicator="blue"
            )
            
            return {"success": True, "total": len(orders), "job_id": job.id, "queued": True}
        else:
            # 小批量直接处理
            sync_service = OrderSyncService()
            results = {"success": 0, "failed": 0, "details": []}
            
            for order in orders:
                result = sync_service.refresh_order_from_raw_data(order.name)
                if result['success']:
                    results["success"] += 1
                else:
                    results["failed"] += 1
                    results["details"].append({
                        "order": order.order_id_code,
                        "error": result["message"]
                    })
            
            frappe.msgprint(
                f"批量刷新完成！成功: {results['success']}, 失败: {results['failed']}",
                title="批量刷新",
                indicator="green" if results["failed"] == 0 else "orange"
            )
            
            return {"success": True, "total": len(orders), "results": results}
        
    except Exception as e:
        frappe.log_error(f"批量刷新订单失败: {str(e)}")
        frappe.msgprint(f"批量刷新失败: {str(e)}", title="错误", indicator="red")
        return {'success': False, 'error': str(e)}


def process_bulk_refresh_queue(order_names: List[str]):
    """队列处理批量刷新"""
    try:
        sync_service = OrderSyncService()
        results = {"success": 0, "failed": 0, "details": []}
        
        for order_name in order_names:
            try:
                result = sync_service.refresh_order_from_raw_data(order_name)
                if result['success']:
                    results["success"] += 1
                else:
                    results["failed"] += 1
                    results["details"].append({
                        "order": order_name,
                        "error": result["message"]
                    })
                    
                # 每处理10个订单提交一次数据库
                if (results["success"] + results["failed"]) % 10 == 0:
                    frappe.db.commit()
                    
            except Exception as e:
                results["failed"] += 1
                results["details"].append({
                    "order": order_name,
                    "error": str(e)
                })
                frappe.log_error(f"队列处理订单刷新失败 {order_name}: {str(e)}")
        
        # 最终提交
        frappe.db.commit()
        
        # 记录完成日志
        frappe.logger().info(f"批量刷新队列完成: 成功 {results['success']}, 失败 {results['failed']}")
        
        return results
        
    except Exception as e:
        frappe.log_error(f"批量刷新队列处理失败: {str(e)}")
        raise


@frappe.whitelist()
def rematch_sku_for_orders(order_names: str = None):
    """重新匹配订单的SKU"""
    try:
        import json
        
        if order_names:
            names = json.loads(order_names) if isinstance(order_names, str) else order_names
            filters = {"name": ["in", names]}
        else:
            # 查找所有未匹配的订单
            filters = {"match_status": "未匹配"}
        
        orders = frappe.get_all("Tongtool Order", 
            filters=filters,
            fields=["name", "order_id_code"]
        )
        
        if not orders:
            frappe.msgprint("没有找到需要重新匹配的订单", indicator="orange")
            return {"success": True, "total": 0}
        
        matched_count = 0
        processed_count = 0
        
        for order_info in orders:
            try:
                order = frappe.get_doc("Tongtool Order", order_info.name)
                order_matched = False
                
                for item in order.order_items:
                    if item.match_status == '未匹配' and item.tongtool_sku:
                        # 重新匹配SKU
                        sync_service = OrderSyncService()
                        erp_item_code = sync_service._find_erp_item_by_tongtool_sku(item.tongtool_sku)
                        
                        if erp_item_code:
                            item.erp_item_code = erp_item_code
                            item.match_status = '已匹配'
                            
                            # 更新物料成本
                            try:
                                item.item_cost = frappe.db.get_value("Item", erp_item_code, "standard_rate") or 0
                            except:
                                item.item_cost = 0
                            
                            order_matched = True
                
                if order_matched:
                    # 更新订单匹配状态
                    unmatched_items = [item for item in order.order_items if item.match_status == '未匹配']
                    order.match_status = '未匹配' if unmatched_items else '已匹配'
                    
                    order.save()
                    matched_count += 1
                
                processed_count += 1
                
                # 每处理20个订单提交一次
                if processed_count % 20 == 0:
                    frappe.db.commit()
                
            except Exception as e:
                frappe.log_error(f"重新匹配订单失败 {order_info.order_id_code}: {str(e)}")
        
        frappe.db.commit()
        
        frappe.msgprint(
            f"SKU重新匹配完成！处理 {processed_count} 个订单，匹配成功 {matched_count} 个",
            title="重新匹配",
            indicator="green"
        )
        
        return {
            "success": True, 
            "processed": processed_count, 
            "matched": matched_count
        }
        
    except Exception as e:
        frappe.log_error(f"重新匹配SKU失败: {str(e)}")
        frappe.msgprint(f"重新匹配失败: {str(e)}", title="错误", indicator="red")
        return {'success': False, 'error': str(e)}


@frappe.whitelist()
def auto_refresh_orders():
    """自动刷新订单（定时任务）"""
    try:
        settings = frappe.get_single('Tongtool Settings')
        
        if not settings.enable_auto_refresh:
            return {"success": True, "message": "自动刷新未启用"}
        
        # 检查是否需要执行（根据频率设置）
        if settings.auto_refresh_frequency == "Daily":
            # 每天执行
            pass
        elif settings.auto_refresh_frequency == "Weekly":
            # 只在周日执行
            import datetime
            if datetime.datetime.now().weekday() != 6:  # 6是周日
                return {"success": True, "message": "非周日，跳过周度刷新"}
        
        # 执行批量刷新
        result = bulk_refresh_orders(
            use_queue=True
        )
        
        # 更新最后刷新时间
        settings.last_refresh_time = frappe.utils.now()
        settings.save()
        
        frappe.logger().info(f"自动刷新订单完成: {result}")
        return result
        
    except Exception as e:
        frappe.log_error(f"自动刷新订单失败: {str(e)}")
        return {'success': False, 'error': str(e)}


def weekly_data_refresh():
    """周度数据刷新（定时任务）"""
    try:
        settings = frappe.get_single('Tongtool Settings')
        
        if not settings.enable_auto_refresh:
            return
        
        # 执行全面的数据刷新
        # 获取需要刷新的订单列表
        order_names_set = set()
        
        # 查找未匹配的订单
        unmatched_orders = frappe.get_all("Tongtool Order", 
            filters={"match_status": "未匹配"},
            pluck="name"
        )
        order_names_set.update(unmatched_orders)
        
        # 查找sale_account为空的订单
        empty_account_orders = frappe.get_all("Tongtool Order", 
            filters={"sale_account": ["in", ["", "None", None]]},
            pluck="name"
        )
        order_names_set.update(empty_account_orders)
        
        # 查找channel为空的订单
        empty_channel_orders = frappe.get_all("Tongtool Order", 
            filters={"channel": ["in", ["", "None", None]]},
            pluck="name"
        )
        order_names_set.update(empty_channel_orders)
        
        if order_names_set:
            frappe.enqueue(
                'tongtool_integration.sync.order_sync.process_bulk_refresh_queue',
                queue='default',
                timeout=7200,  # 2小时超时
                order_names=list(order_names_set),
                now=False
            )
        
        frappe.logger().info("周度数据刷新任务已启动")
        
    except Exception as e:
        frappe.log_error(f"周度数据刷新失败: {str(e)}")


@frappe.whitelist()
def manual_sync(start_date: str, end_date: str = None):
    """手动同步指定日期范围的订单"""
    try:
        if not end_date:
            end_date = start_date
        
        sync_service = OrderSyncService()
        
        # 按天循环同步
        current_date = get_datetime(start_date).date()
        end_date_obj = get_datetime(end_date).date()
        
        total_result = {
            'dates': [],
            'total_self_fulfillment': {'total': 0, 'created': 0, 'updated': 0, 'errors': 0},
            'total_fba': {'total': 0, 'created': 0, 'updated': 0, 'errors': 0},
            'errors': []
        }
        
        while current_date <= end_date_obj:
            date_str = current_date.strftime('%Y-%m-%d')
            result = sync_service.sync_daily_orders(date_str)
            
            total_result['dates'].append(result)
            
            # 累计统计
            for key in ['total', 'created', 'updated', 'errors']:
                total_result['total_self_fulfillment'][key] += result['self_fulfillment'][key]
                total_result['total_fba'][key] += result['fba'][key]
            
            total_result['errors'].extend(result['errors'])
            
            current_date += timedelta(days=1)
        
        return total_result
        
    except Exception as e:
        frappe.log_error(f"手动同步订单失败: {str(e)}")
        return {'error': str(e)}


def send_sync_error_notification(result: Dict, email: str):
    """发送同步错误通知"""
    try:
        subject = f"通途订单同步错误 - {result['date']}"
        
        message = f"""
        订单同步完成，但有错误发生：
        
        日期: {result['date']}
        
        自发货订单:
        - 总计: {result['self_fulfillment']['total']}
        - 创建: {result['self_fulfillment']['created']}
        - 更新: {result['self_fulfillment']['updated']}
        - 错误: {result['self_fulfillment']['errors']}
        
        FBA订单:
        - 总计: {result['fba']['total']}
        - 创建: {result['fba']['created']}
        - 更新: {result['fba']['updated']}
        - 错误: {result['fba']['errors']}
        
        错误详情:
        {chr(10).join(result['errors'])}
        """
        
        frappe.sendmail(
            recipients=[email],
            subject=subject,
            message=message
        )
        
    except Exception as e:
        frappe.log_error(f"发送同步错误通知失败: {str(e)}")
